package com.eee.machine.service.impl;

import com.eee.machine.beans.TChannelProduct;
import com.eee.machine.beans.TMachine;
import com.eee.machine.common.*;
import com.eee.machine.concurrent.CustomThreadPool;
import com.eee.machine.concurrent.OrderHashMap;
import com.eee.machine.configuration.StoreConfig;
import com.eee.machine.dao.mapper.TChannelProductMapper;
import com.eee.machine.dao.mapper.TMachineMapper;
import com.eee.machine.dao.mapper.TMemberMachineMapper;
import com.eee.machine.service.IMachineService;
import com.eee.machine.service.IOrderService;
import com.eee.machine.utils.youzan.TokenUtil;
import com.youzan.open.sdk.client.auth.Token;
import com.youzan.open.sdk.client.core.DefaultYZClient;
import com.youzan.open.sdk.client.core.YZClient;
import com.youzan.open.sdk.client.oauth.model.OAuthToken;
import com.youzan.open.sdk.gen.v3_0_0.api.YouzanRetailOpenSpuQuery;
import com.youzan.open.sdk.gen.v3_0_0.api.YouzanSalesmanAccountsGet;
import com.youzan.open.sdk.gen.v3_0_0.api.YouzanSalesmanTradesAccountGet;
import com.youzan.open.sdk.gen.v3_0_0.api.YouzanTradeRefundSellerActive;
import com.youzan.open.sdk.gen.v3_0_0.model.*;
import com.youzan.open.sdk.gen.v4_0_0.api.YouzanTradeGet;
import com.youzan.open.sdk.gen.v4_0_0.api.YouzanTradesSoldGet;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradeGetParams;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradeGetResult;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradesSoldGetParams;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradesSoldGetResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

@Service
public class IOrderServiceImpl implements IOrderService {

    private final static Logger logger = LoggerFactory.getLogger(IOrderServiceImpl.class);

    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private StoreConfig storeConfig;
    @Autowired
    private IMachineService machineService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private TMachineMapper machineMapper;
    @Autowired
    private TMemberMachineMapper tMemberMachineMapper;
    @Autowired
    private TChannelProductMapper channelProductMapper;


    @Override
    public TableData getOrderList(Long page, Long pageSize) {
        String accessToken = tokenUtil.getAccessToken();
        System.out.println("授权token====="+accessToken);
//        OAuthToken token = TokenUtil.getToken();
        YZClient client = new DefaultYZClient(new Token(accessToken)); //new Sign(appKey, appSecret)
        YouzanTradesSoldGetParams youzanTradesSoldGetParams = new YouzanTradesSoldGetParams();
        youzanTradesSoldGetParams.setPageSize(pageSize);
        youzanTradesSoldGetParams.setPageNo(page);
        YouzanTradesSoldGet youzanTradesSoldGet = new YouzanTradesSoldGet();
        youzanTradesSoldGet.setAPIParams(youzanTradesSoldGetParams);
        YouzanTradesSoldGetResult result = client.invoke(youzanTradesSoldGet);
        YouzanTradesSoldGetResult.StructurizationTrade[] fullOrderInfoList = result.getFullOrderInfoList();
        List<OrderBean> resultList = new ArrayList<>();
        Arrays.stream(fullOrderInfoList).forEach(item->{
            YouzanTradesSoldGetResult.StructurizationTradeOrderInfo fullOrderInfo = item.getFullOrderInfo();
            OrderBean orderBean = new OrderBean();
            orderBean.setCreateTime(fullOrderInfo.getOrderInfo().getCreated());
            orderBean.setOrderType(fullOrderInfo.getOrderInfo().getType());
            orderBean.setOrderStatus(fullOrderInfo.getOrderInfo().getStatus());
            orderBean.setOrderStatusStr(fullOrderInfo.getOrderInfo().getStatusStr());
            orderBean.setTid(fullOrderInfo.getOrderInfo().getTid());

            OrderBean.Buyer buyer = new OrderBean.Buyer();
            buyer.setBuyerId(fullOrderInfo.getBuyerInfo().getBuyerId());
            buyer.setBuyerPhone(fullOrderInfo.getBuyerInfo().getBuyerPhone());
            buyer.setFansId(fullOrderInfo.getBuyerInfo().getFansId());
            buyer.setFansType(fullOrderInfo.getBuyerInfo().getFansType());
            buyer.setFansNickname(fullOrderInfo.getBuyerInfo().getFansNickname());
            /*设置购买人信息*/
            orderBean.setBuyer(buyer);

            OrderBean.PayInfo payInfo = new OrderBean.PayInfo();
            payInfo.setOuterTransactions(fullOrderInfo.getPayInfo().getOuterTransactions());
            payInfo.setPayment(fullOrderInfo.getPayInfo().getPayment());
            payInfo.setTotalFee(fullOrderInfo.getPayInfo().getTotalFee());
            payInfo.setTransaction(fullOrderInfo.getPayInfo().getTransaction());
            /*设置支付信息*/
            orderBean.setPayInfo(payInfo);

            OrderBean.TradeSource tradeSource = new  OrderBean.TradeSource();
            tradeSource.setPlatform(fullOrderInfo.getSourceInfo().getSource().getPlatform());
            tradeSource.setWxEntrance(fullOrderInfo.getSourceInfo().getSource().getWxEntrance());
            orderBean.setTradeSource(tradeSource);

            OrderBean.OrderItems[] items = new OrderBean.OrderItems[fullOrderInfo.getOrders().length];
            YouzanTradesSoldGetResult.StructurizationTradeItemDetail[] orders = fullOrderInfo.getOrders();
            for(int i=0; i< fullOrderInfo.getOrders().length; i++){
                YouzanTradesSoldGetResult.StructurizationTradeItemDetail good = orders[i];
                OrderBean.OrderItems orderItem = new OrderBean.OrderItems();
                orderItem.setItemId(good.getItemId());
                orderItem.setItemType(good.getItemType());
                orderItem.setNum(good.getNum());
                orderItem.setOid(good.getOid());
                orderItem.setPicPath(good.getPicPath());
                orderItem.setTitle(good.getTitle());
                orderItem.setTotalFee(good.getTotalFee());
                items[i] = orderItem;
            }
            /*设置订单商品信息*/
            orderBean.setOrderItems(items);
            resultList.add(orderBean);
        });
        TableData resultObject = new TableData("获取数据成功", 0 , result.getTotalResults().intValue(),resultList);
        return resultObject;
    }

    @Override
    public OperateResponse refundSell(String tid, Float refundFee, String desc, String oid) {
//        OAuthToken token = TokenUtil.getToken();
//        YZClient client = new DefaultYZClient(new Token(token.getAccessToken())); //new Sign(appKey, appSecret)
        String accessToken = tokenUtil.getAccessToken();
        System.out.println("授权token====="+accessToken);
//        OAuthToken token = TokenUtil.getToken();
        YZClient client = new DefaultYZClient(new Token(accessToken)); //new Sign(appKey, appSecret)
        YouzanTradeRefundSellerActiveParams youzanTradeRefundSellerActiveParams = new YouzanTradeRefundSellerActiveParams();
        youzanTradeRefundSellerActiveParams.setTid(tid);
        youzanTradeRefundSellerActiveParams.setDesc(desc);
        youzanTradeRefundSellerActiveParams.setRefundFee(refundFee);
        youzanTradeRefundSellerActiveParams.setOid(Long.parseLong(oid));
        YouzanTradeRefundSellerActive youzanTradeRefundSellerActive = new YouzanTradeRefundSellerActive();
        youzanTradeRefundSellerActive.setAPIParams(youzanTradeRefundSellerActiveParams);
        YouzanTradeRefundSellerActiveResult result = client.invoke(youzanTradeRefundSellerActive);
        if(result.getIsSuccess()){
            return OperateResponse.obtainSuccessResponse(result.getRefundId());
        }else{
            return OperateResponse.failResponse("退款失败");
        }
    }

    @Override
    public JSONObject makeOrder(MsgPushEntity msgPushEntity) {
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "success");
        if (msgPushEntity.isTest()) {
            return res;
        }
        //判断消息是否合法
//        String sign= MD5.digest(clientId+entity.getMsg()+clientSecret);
//        if (!sign.equals(entity.getSign())){
//            return res;
//        }

        // 对于msg 先进行URI解码
        String msg="";
        try {
            msg= URLDecoder.decode(msgPushEntity.getMsg(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        logger.info("MsgPushEntity消息体======{}",msgPushEntity.toString());
        logger.info("msg消息体======{}",msg);
        logger.info("订单ID======{}",msgPushEntity.getId());
        CustomThreadPool.fixedThreadPool.execute(new dealOrderMsgThread(msg, msgPushEntity.getId()));
        return res;
    }

    @Override
    public String getSaleManIdByTradeId(String orderNo) {
//        OAuthToken token = TokenUtil.getToken();
//        YZClient client = new DefaultYZClient(new Token(token.getAccessToken())); //new Sign(appKey, appSecret)
        String accessToken = tokenUtil.getAccessToken();
        System.out.println("授权token====="+accessToken);
        YZClient client = new DefaultYZClient(new Token(accessToken)); //new Sign(appKey, appSecret)
        YouzanSalesmanTradesAccountGetParams youzanSalesmanTradesAccountGetParams = new YouzanSalesmanTradesAccountGetParams();
        youzanSalesmanTradesAccountGetParams.setOrderNo(orderNo);
        YouzanSalesmanTradesAccountGet youzanSalesmanTradesAccountGet = new YouzanSalesmanTradesAccountGet();
        youzanSalesmanTradesAccountGet.setAPIParams(youzanSalesmanTradesAccountGetParams);
        YouzanSalesmanTradesAccountGetResult result = client.invoke(youzanSalesmanTradesAccountGet);
        return result.getMobile();
//        return tMemberMachineMapper.getSaleManBindMachineId(saleManPhone);
    }

    @Override
    public List getTradeByTrade(String tradeId) {
//        OAuthToken token = TokenUtil.getToken();
//        YZClient client = new DefaultYZClient(new Token(token.getAccessToken())); //new Sign(appKey, appSecret)
        String accessToken = tokenUtil.getAccessToken();
        System.out.println("授权token====="+accessToken);
        YZClient client = new DefaultYZClient(new Token(accessToken));
        YouzanTradeGetParams youzanTradeGetParams = new YouzanTradeGetParams();
        youzanTradeGetParams.setTid(tradeId);
        YouzanTradeGet youzanTradeGet = new YouzanTradeGet();
        youzanTradeGet.setAPIParams(youzanTradeGetParams);
        YouzanTradeGetResult result = client.invoke(youzanTradeGet);
        YouzanTradeGetResult.StructurizationTradeOrderInfo fullOrderInfo = result.getFullOrderInfo();
        YouzanTradeGetResult.StructurizationTradeItemDetail[] orders = fullOrderInfo.getOrders();
        LinkedList<Map<String, Object>> items = new LinkedList<Map<String, Object>>();
        Arrays.stream(orders).forEach((item)->{
            System.out.println("商品itemID==="+item.getItemId());
            Map<String, Object> map = new HashMap<String, Object>();
            Long itemId = item.getItemId();
            int num = item.getNum().intValue();
            map.put("num", num);
            map.put("itemId", itemId);
            items.add(map);
        });
        return items;
    }

    public class dealOrderMsgThread implements Runnable{
        private String msg;
        private String tradeId;

        public dealOrderMsgThread(String msg, String tradeId) {
            this.msg = msg;
            this.tradeId = tradeId;
        }

        @Override
        public void run() {
            String saleManPhone = getSaleManIdByTradeId(tradeId);
            System.out.println("分销员手机号==" + saleManPhone);
            System.out.println("订单Id==" + tradeId);
            String machineId = tMemberMachineMapper.getSaleManBindMachineId(saleManPhone);
            TMachine tMachine = machineMapper.selectByPrimaryKey(machineId);
            float totalPrice = 0L;
                JSONObject msgObject = JSONObject.fromObject(msg);
                JSONObject payFullInfo = msgObject.getJSONObject("full_order_info");
                JSONObject payInfo = payFullInfo.getJSONObject("pay_info");
                String payment = payInfo.getString("payment");      //订单总价
                JSONArray orders = payFullInfo.getJSONArray("orders");
                JSONObject firstOrder = (JSONObject)orders.get(0);
                String oid = firstOrder.getString("oid");       //第一个订单明细ID
                if(tMachine == null || tMachine.getStatus() != 1){      //机器故障退款
                    orderService.refundSell(tradeId, Float.valueOf(payment),"机器故障退款" , oid);
                }else{
                //订单出货数据
                LinkedList<OrderItem> resultList = new LinkedList<OrderItem>();
                LinkedList<Map<Long, Integer>> itemList = new LinkedList<>();
                for (Object object : orders) {
                    JSONObject orderObject = (JSONObject) object;
                    String orderOid = firstOrder.getString("oid");
                    int num = orderObject.getInt("num");
                    long itemId = orderObject.getLong("item_id");
                    List<TChannelProduct> surplusProduct = channelProductMapper.getSurplusProduct(machineId, String.valueOf(itemId));
                    Integer productSurplusNum = 0;
                    for (TChannelProduct channelProduct : surplusProduct) {
                        Integer productNum = channelProduct.getProductNum();
                        productSurplusNum += productNum;
                    }
                    if (productSurplusNum < num) {    //缺货退款
                        orderService.refundSell(tradeId, Float.valueOf(payment),"商品缺货退款" , orderOid);
                        resultList.clear();
                        break;
                    } else {
                        for (TChannelProduct channelProduct : surplusProduct) {
                            OrderItem orderItem = new OrderItem();
                            String s = channelProduct.gettChannelId();
                            Integer lineNum = channelProduct.getProductNum();
                            orderItem.setCount(num);
                            orderItem.setLineSort(Integer.parseInt(s.substring(s.length() - 1)));
                            orderItem.setTrade(tradeId);
                            resultList.add(orderItem);
                            channelProductMapper.decreaseProduct(lineNum-num, s);
                            if (lineNum >= num) {
                                break;
                            }
                        }
                    }
                }
                if (resultList.size() > 0) {
                    OrderHashMap.getSingleton().addOrderItem(machineId,resultList);
                }
            }
        }
        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public String getTradeId() {
            return tradeId;
        }

        public void setTradeId(String tradeId) {
            this.tradeId = tradeId;
        }

    }
}
